package com.shujia;


import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.HashSet;
import java.util.Properties;
import java.util.Scanner;

public class Code03UpdateCache {
    public static void main(String[] args) throws ClassNotFoundException, IOException, SQLException {
        /*
            实现如下功能:
                通过输入用户名和密码对 Mysql数据库中的数据进行做查询，并将结果进行返回，同时再整个架构中插入Redis做数据的缓存
                    实现效果为：
                        1. 先从Redis中查询对应的数据，如果有数据，那么直接返回
                        2. 如果没有数据，那么需要从Mysql中进行数据查询，并将结果返回，同时将数据保存至Redis中

         */

        // 加载配置对象
        Properties properties = new Properties();
        properties.load(new FileReader("redisCode/src/main/resources/mysql.properties"));


        // 创建Mysql连接对象
        Class.forName("com.mysql.jdbc.Driver");
        String mysqlUser = properties.getProperty("user");
        String mysqlPasswd = properties.getProperty("passwd");
        String url = properties.getProperty("url");
        Connection connection = DriverManager.getConnection(url, mysqlUser, mysqlPasswd);

        // 创建Jedis对象
        HashSet<HostAndPort> hostAndPorts = new HashSet<>();
        hostAndPorts.add(new HostAndPort("192.168.163.100", 6380));
        hostAndPorts.add(new HostAndPort("192.168.163.100", 6381));
        hostAndPorts.add(new HostAndPort("192.168.163.100", 6382));

        JedisCluster jedisCluster = new JedisCluster(hostAndPorts);


        // 解决输入问题：
        Scanner scanner = new Scanner(System.in);
        // 登录
        boolean login = login(scanner, jedisCluster, connection);

        if (login) {
            System.out.println("是否需要修改密码：1是 0否");
            if (scanner.hasNextInt()) {
                int flag = scanner.nextInt();
                if (flag == 1) {
                    System.out.println("请输入用户名:");
                    String user = "";
                    if (scanner.hasNext()) {
                        user = scanner.next();
                    }
                    System.out.println("请输入新密码:");
                    String passwd = "";
                    if (scanner.hasNext()) {
                        passwd = scanner.next();
                    }

                    // 调用函数更新密码
                    updateDataToMysql(jedisCluster, connection, user, passwd);


                }

            }
        }
        // 关闭资源
        connection.close();
        jedisCluster.close();


    }

    public static boolean login(Scanner scanner, JedisCluster jedis, Connection mysqlCon) throws SQLException {
        System.out.println("欢迎登录大数据26期集训营");
        System.out.println("=====================");
        System.out.println("请输入用户名:");
        String user = "";
        if (scanner.hasNext()) {
            user = scanner.next();
        }

        System.out.println("请输入密码:");
        String passwd = "";
        if (scanner.hasNext()) {
            passwd = scanner.next();
        }
        String findPasswd = findDataFromRedis(jedis, mysqlCon, user);


//        String findPasswd = findDataFromMysql(jedisCluster,connection, user);
//

        if (findPasswd.equals(passwd)) {
            System.out.println("登录成功");
            return true;
        } else {
            System.out.println("登录失败");
            return false;
        }

    }


    public static void updateDataToMysql(JedisCluster jedis, Connection mysqlCon, String user, String passwd) throws SQLException {
        // 1.从Mysql中执行SQL语句更新SQL
        PreparedStatement preparedStatement = mysqlCon.prepareStatement("update bigdata_user set passwd = ? where user=?");
        preparedStatement.setString(2, user);
        preparedStatement.setString(1, passwd);
        // 执行得到更新结果i 表示影响的行数 有更新则是1 否则为0
        int i = preparedStatement.executeUpdate();
        if (i > 0) {
            // 2.调用Redis做数据更新
            insertDataToRedis(jedis, user, passwd);
            System.out.println("redis更新了");
        }


    }


    public static String findDataFromRedis(JedisCluster jedis, Connection mysqlCon, String user) throws SQLException {
        String passwd = jedis.get(user);
        // 如果发现redis中没有数据返回的是null,那么需要从Mysql中进行查询并返回

        if (passwd == null) {
            // 返回的数据直接再返回给调用者
            passwd = findDataFromMysql(jedis, mysqlCon, user);
        }

//        System.out.println(passwd);
        return passwd;
    }


    public static String findDataFromMysql(JedisCluster jedis, Connection mysqlCon, String user) throws SQLException {
        PreparedStatement preparedStatement = mysqlCon.prepareStatement("select * from bigdata_user where user =?");

        preparedStatement.setString(1, user);

        ResultSet resultSet = preparedStatement.executeQuery();

        String mysqlPs = null;
        if (resultSet.next()) {
            System.out.println("Mysql查询到数据");
            mysqlPs = resultSet.getString("passwd");
            // 当Mysql中查询到数据后，需要将数据缓存至Redis中
            insertDataToRedis(jedis, user, mysqlPs);
        }
        return mysqlPs;
    }


    public static void insertDataToRedis(JedisCluster jedis, String key, String value) {
        // 对同一个Key做数据插入，那么会覆盖原先的数据
        jedis.set(key, value);
        System.out.println("用户信息：" + key + "已经被插入到Redis中");
    }
}
